<script setup lang="ts">
import { ref, reactive, nextTick, onUnmounted } from "vue";
import type {
  VxeGridProps,
  VxeGridInstance,
  VxeToolbarInstance
} from "vxe-table";
import { CommonUtils } from "@/utils/common/commonUtil";

import { RefreshRight, Search } from "@element-plus/icons-vue";

import { searchActionApi } from "@/api/user";

// import CryptoJS from "crypto-js";

defineOptions({
  name: "ChooseUserGroupDialog"
});

const emit = defineEmits(["cell-click"]);

const toolbarRef = ref<VxeToolbarInstance>();
const xGrid2 = ref({} as VxeGridInstance);

const visible = ref(false);

interface RowVO {
  userGroupId: string;
  description: string;
}

const gridOptions = reactive<VxeGridProps<RowVO>>({
  height: "260px",
  columns: [
    { title: " ", type: "seq", width: 50, sortable: true },
    {
      title: "User Group ID",
      field: "userGroupId",
      sortable: true
    },
    {
      title: "Description",
      field: "description",
      sortable: true
    }
  ],
  data: [],
  stripe: true,
  rowConfig: { keyField: "userGroupId" }
});

const page = ref({
  pageSize: 10,
  total: gridOptions.data.length
});

const userGroupId = ref("");

let sortable2: any;

const columnDrop = () => {
  sortable2 = CommonUtils.columnDrop(xGrid2);
};

let initTime: any;

//清除
onUnmounted(() => {
  clearTimeout(initTime);
  if (sortable2) {
    sortable2.destroy();
  }
});

const uuidv4 = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

// 查询数据
const getUserGroupList = () => {
  searchActionApi({
    urlParams: {
      _dc: new Date().getTime()
    },
    formData: {
      head: {
        appId: "webui",
        charset: "utf-8",
        facilityRrn: "1",
        format: "json",
        method: "search",
        timestamp: new Date().getTime(),
        transactionId: uuidv4(),
        userId: "ADMIN",
        version: ""
      },
      body: {
        // columns: CryptoJS.AES.encrypt("INSTANCE_ID,INSTANCE_DESC"),
        columns: "P7aBBMllwkiEPu+EzTjShLdyczlnW5BZLOg5Wsim5sqMd1dHjmAycCQ=",
        // dataPermission: CryptoJS.AES.encrypt("false"),
        dataPermission: "EJm+I+1bwgMZlorr8pBz3NueAmGv",
        descFlag: "",
        // keyColumn: CryptoJS.AES.encrypt("INSTANCE_ID"),
        keyColumn: "P7aBBMllwkiEPu+sMKWEIulwrwRYZu0D8kvX",
        limit: 10,
        orderBy: "",
        page: 1,
        parameters: { search_INSTANCE_ID: userGroupId.value },
        search_INSTANCE_ID: userGroupId.value,
        searchcolume: "null",
        start: 0,
        // strWhere: CryptoJS.AES.encrypt(
        //   "OBJECT='USERGROUP' AND NAMED_SPACE = 'MYCIM2'"
        // ),
        strWhere:
          "ObqYFct/vCqOJO76wyTOhaYbED12W/VELmAls1kDC/ZmtP5bz3wbVCpOxtRCEjZgizgzU1nq12OC4Kl2iw==",
        // tableID: CryptoJS.AES.encrypt("NAMED_OBJECT")
        tableID: "OLmfFcx0zk+RMuj8e+GPThMiHzAiSbT75mgPww=="
      }
    }
  }).then((res: any) => {
    gridOptions.data = res.body.results.map(item => {
      return {
        userGroupId: item.INSTANCE_ID,
        description: item.INSTANCE_DESC
      };
    });
    page.value.total = gridOptions.data.length;
  });
};

const cellClickEvent = ({ row }) => {
  console.log(row);
  emit("cell-click", row.userGroupId);
  close();
};

// 打开弹窗
const open = searchData => {
  userGroupId.value = searchData;
  getUserGroupList();
  gridOptions.data = [];
  page.value.total = 0;
  visible.value = true;
  nextTick(() => {
    // 加载完成之后在绑定拖动事件
    initTime = setTimeout(() => {
      columnDrop();
    }, 500);
    if (toolbarRef.value && xGrid2.value) {
      xGrid2.value.connect(toolbarRef.value);
    }
  });
};

// 关闭弹窗
const close = () => {
  visible.value = false;
};

defineExpose({
  open,
  close
});
</script>

<template>
  <el-dialog
    title="Query Condition"
    append-to-body
    class="choose-user-group-dialog"
    v-model="visible"
    draggable
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="content">
      <div class="search-info">
        <div class="label">User Group ID:</div>
        <el-input v-model="userGroupId" style="width: 200px" />
      </div>
      <div class="operation">
        <el-button type="primary" :icon="Search" @click="getUserGroupList">
          Query
        </el-button>
      </div>
      <div class="title">
        Info. List
        <vxe-toolbar
          ref="toolbarRef"
          size="mini"
          :custom="{
            immediate: true,
            showFooter: false,
            allowFixed: false
          }"
        ></vxe-toolbar>
      </div>
      <vxe-grid
        ref="xGrid2"
        v-bind="gridOptions"
        @cell-click="cellClickEvent"
      />
    </div>

    <template #footer>
      <vxe-pager
        v-model:page-size="page.pageSize"
        :total="page.total"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'Jump',
          'PageCount',
          'NextPage',
          'NextJump',
          'Sizes',
          'Total'
        ]"
      >
        <template #left>
          <el-button :icon="RefreshRight" />
        </template>
      </vxe-pager>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.choose-user-group-dialog {
  .el-dialog__header {
    display: flex;
    align-items: center;
    height: 36px;
    margin: 0;
    padding: 0 20px;
    background: rgba(43, 83, 135, 1);
    border-color: rgba(43, 83, 135, 1);

    .el-dialog__title {
      color: #fff;
      font-size: 14px;
      font-weight: 700;
      font-family: arial, helvetica, verdana, sans-serif;
    }

    .el-dialog__headerbtn {
      right: 16px;
      width: 16px;
      height: 16px;

      .el-icon {
        color: #fff !important;
        background: none !important;
      }
    }
  }

  .el-dialog__body {
    padding: 0;
    border: solid 1px rgba(43, 83, 135, 1);
    .content {
      .search-info {
        display: flex;
        border: solid 1px rgba(43, 83, 135, 1);
        padding: 6px 0;
        .label {
          width: 120px;
          line-height: 32px;
          text-align: right;
          margin-right: 12px;
          color: #000;
        }
      }
    }

    .operation {
      padding: 6px 6px 6px 0;
      text-align: right;
      background-color: #dfeaf2;
    }

    .title {
      display: flex;
      justify-content: space-between;
      background: rgba(43, 83, 135, 1);
      color: #fff;
      padding: 6px 20px;
      line-height: 32px;
      font-size: 14px;
      font-weight: 700;
      font-family: arial, helvetica, verdana, sans-serif;

      .vxe-toolbar {
        padding: 0;

        .vxe-custom--wrapper {
          margin-left: 0;
          background: rgba(43, 83, 135, 1);

          .vxe-button {
            color: rgb(43, 83, 135);
            font-size: 8px;
            min-width: 20px;
            height: 20px;
          }

          // 不展示全选
          .vxe-custom--header {
            display: none;
          }
        }
      }
    }

    .vxe-cell--title,
    .vxe-cell--label {
      font-size: 16px;
      font-weight: normal;
      color: #000000;
    }
  }

  .el-dialog__footer {
    padding: 10px;
    .vxe-pager {
      --vxe-table-row-height-medium: 32px;
      .vxe-pager--wrapper {
        width: 100%;
        display: flex;
        align-items: center;

        .vxe-pager--total {
          margin-left: auto;
        }
      }
    }
  }
}
</style>
